using System;
using System.Linq.Expressions;

namespace MvvmUtils.ViewModels
{
    public class ComputedProperty<TOwnerViewModel, TProperty> : IProperty
        where TOwnerViewModel : ViewModel
    {
        private readonly string _propertyName;
        private readonly TOwnerViewModel _ownerViewModel;
        private readonly Func<TOwnerViewModel, TProperty> _valueComputer;

        public ComputedProperty(
            string propertyName,
            Expression<Func<TOwnerViewModel, TProperty>> valueComputer, 
            TOwnerViewModel ownerViewModel)
        {
            if (valueComputer == null) throw new ArgumentNullException("valueComputer");
            if (ownerViewModel == null) throw new ArgumentNullException("ownerViewModel");
            if(string.IsNullOrEmpty(propertyName)) throw new ArgumentException("Empty property name.", "propertyName");

            _propertyName = propertyName;
            _ownerViewModel = ownerViewModel;
            _valueComputer = valueComputer.Compile();
        }

        public string Name
        {
            get { return _propertyName; }
        }

        public TProperty GetValue()
        {
            return _valueComputer(_ownerViewModel);
        }
    }
}